﻿using Comm100.Framework.Tenancy;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Concurrent;

namespace Bot.Domain
{
    public class BotTenantProvider : ITenancyResolver
    {
        private static ConcurrentDictionary<int, Tenant> tenants = new ConcurrentDictionary<int, Tenant>(); // cache tenant config

        private Tenant _tenant = null;

        public BotTenantProvider(IHttpContextAccessor accessor)
        {
            var host = accessor.HttpContext.Request.Host.Value;

            // get from database by host if use subdomain, if complete the site database merge, also need get the database name from the database
            var id = Convert.ToInt32(accessor.HttpContext.Request.Query["siteId"]);

            this._tenant = tenants.GetOrAdd(id, new Tenant()
            {
                Id = id,
                DatabaseName = GetDbName(id),
                Host = host
            });
        }

        private string GetDbName(int siteId)    // read from db
        {
            if(siteId > 0)
            {
                return "Bot.Site" + (siteId / 500 + 1);
            }
            return "Bot.Site2001";
        }

        public Tenant GetTenant()
        {
            return _tenant;
        }
    }
}
